<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { computed, ref } from 'vue';
import { useLocale } from '@/locale/locale';
import { useCheckoutStore } from '@/store/checkout';
import { usePopupStore } from '@/store/popup';

const props = withDefaults(defineProps<{ bookersNumber: number; maxBookersNumber: number }>(), {
  bookersNumber: 1,
  maxBookersNumber: 5
});

const emit = defineEmits<{ update: [bookersNumber: number, v2: number, v3: number] }>();

const { t } = useLocale();
const checkoutStore = useCheckoutStore();
const popupStore = usePopupStore();
const { bookersNumberPickerRef } = storeToRefs(popupStore);

const current = ref(1);
popupStore.onOpened('BOOKER_NUMBER', () => {
  // 在当前人数和最大人数中取最小值
  // 并将取到的最小值同步到外部数据源
  current.value = Math.min(props.bookersNumber, props.maxBookersNumber);
  if (props.bookersNumber > props.maxBookersNumber) {
    checkoutStore.setBookersNumber(props.maxBookersNumber, 0, 0);
  }
});

const person = computed(() => {
  return t('LHTKey_hotelPerson');
});

function handleConfirm() {
  popupStore.closeBookersNumberPicker();
  emit('update', current.value, 0, 0);
}
</script>

<template>
  <apt-popup
    ref="bookersNumberPickerRef"
    :cancel-text="t('HomeShortRentReset')"
    :confirm-text="t('LLKey_loginCheckConfirm')"
    :title="t('HomeShortRentSelectPersion')"
    show-cancel-btn
    @cancel="current = 1"
    @close="popupStore.closeBookersNumberPicker"
    @confirm="handleConfirm"
  >
    <view class="mb-2 text-lg text-primary font-medium">
      {{ t('HomeShortRentPersionIn') }}
    </view>
    <view class="mb-3 flex items-center flex-wrap">
      <view
        v-for="i in maxBookersNumber"
        :key="i"
        :class="{ 'is-active': current === i }"
        class="apt-bookers-number-picker__item"
        @click="current = i"
      >
        {{ t('LHTKey_hotelPerson', { person: i }) }}
      </view>
    </view>
    <view class="mb-2 text-lg text-primary font-medium">
      {{ t('HomeShortRentRoom') }}
    </view>
    <view class="mb-10">
      <view class="apt-bookers-number-picker__item is-active">
        {{ t('LHTKey_hotelRoom', { room: 1 }) }}
      </view>
    </view>
  </apt-popup>
</template>

<style lang="scss">
.apt-bookers-number-picker__item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120rpx;
  height: 64rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  background: #f4f4f4;
  border: 2rpx solid #f4f4f4;
  border-radius: 8rpx;
  font-size: 28rpx;
  line-height: 40rpx;
  color: #707070;

  &.is-active {
    background: #e9f5f1;
    border-color: #269c74;
    color: #269c74;
  }
}
</style>
